<?php

namespace App\Models;



use App\User;

class ProductSku extends BaseModel
{
    protected $table = 'products_sku';

    protected $fillable = ['title', 'description', 'price', 'stock','img','vip_price','vip_score'];

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public static function getSku($where)
    {
        $sku = self::where($where)->first();
        if ($sku) {
            $sku = $sku->toArray();
        }
        return $sku;
    }

    public static function getStockCount($product_id)
    {
        $where = [
            ['product_id', '=', $product_id],
            ['stock', '>', '0'],
        ];
        $sum = self::where($where)->sum('stock');
        return $sum;
    }

    public static function getSkuById($id)
    {
        $sku = self::find($id);
        if ($sku) {
            $sku = $sku->toArray();
        }
        return $sku;
    }

    public static function getPriceById($id)
    {
        $sku = self::getSkuById($id);
        $price = 0;
        if ($sku) {
            $price = User::isProxy()?$sku['vip_price']:$sku['price'];
        }
        return $price;
    }

    //获取最低价的个SKU
    public static function getSkuMinPrice($product_id)
    {
        $sku = self::where('product_id', $product_id)->orderBy('price','asc')->first();
        if ($sku) {
            $sku = $sku->toArray();
        }
        return $sku;
    }
}
